package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FieldAttrEntityExt;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 决策树help
 *
 * @Author: hongxiao
 * @date: 2022-01-26 15:29
 */
@Component
public class DecisionTreeHelp {
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private UserTeamHelp userTeamHelp;

    public void handleSummaryList(List<PaasFormDataEntityExt>  paasFormDataESList, Map<String, FieldAttrEntity> explainMap, UserVO userVO) {
        List<Long> contactIdIn = new ArrayList<>();
        paasFormDataESList.forEach(item -> {contactIdIn.add(item.getDataId());});
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(contactIdIn)){
            userTeamHelp.setUserIdMap(contactIdIn, userVO.getCorpid(), XbbRefTypeEnum.CONTACT.getCode(), false, mainUserMap, coUserMap);
        }
        // 当前数据的创建人、负责人、协同人、当前操作人
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            JSONObject data = paasFormDataEntityExt.getData();
            Long dataId = paasFormDataEntityExt.getDataId();
            JSONArray summaryArray;
            JSONArray labelsArray;
            try {
                summaryArray = FastJsonHelper.getJsonArrFromFormData(data, "summaryList");
            } catch (XbbException e) {
                summaryArray = null;
            }
            try {
                labelsArray = FastJsonHelper.getJsonArrFromFormData(data, "labelsList");
            } catch (XbbException e) {
                labelsArray = null;
            }
            if (CollectionsUtil.isNotEmpty(summaryArray)) {
                handlerExplainDTO.setLoginUser(userVO);
                handlerExplainDTO.setOwnerId(mainUserMap.get(dataId));
                handlerExplainDTO.setCoUserId(coUserMap.get(dataId));
                handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
                handlerExplainDTO.setUserId(userVO.getUserId());

                List<SummaryDataPoJo> summaryList = summaryArray.toJavaList(SummaryDataPoJo.class);

                getTextSummaryList(summaryList, explainMap);
                handleSummaryCanSee(summaryList, data, explainMap, handlerExplainDTO, true);
                getNoSpecialSummaryList(summaryList, data);
                data.put("summaryList", summaryList);
            }
            if (CollectionsUtil.isNotEmpty(labelsArray)) {
                handlerExplainDTO.setLoginUser(userVO);
                handlerExplainDTO.setOwnerId(mainUserMap.get(dataId));
                handlerExplainDTO.setCoUserId(coUserMap.get(dataId));
                handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
                handlerExplainDTO.setUserId(userVO.getUserId());

                List<SummaryDataPoJo> labelsList = labelsArray.toJavaList(SummaryDataPoJo.class);
                getTextSummaryList(labelsList, explainMap);
                handleSummaryCanSee(labelsList, data, explainMap, handlerExplainDTO, true);
                getNoSpecialSummaryList(labelsList, data);
                data.put("labelsList", labelsList);
            }
        }

    }

    public List<SummaryDataPoJo> summaryList(JSONObject data, String key, Map<String, FieldAttrEntity> contactExplainMap, HandlerExplainDTO handlerExplainDTO, boolean showPermission) throws XbbException {
        JSONArray array = FastJsonHelper.getJsonArrFromFormData(data, key);
        if (CollectionsUtil.isEmpty(array)) {
            array = new JSONArray();
        }
        List<SummaryDataPoJo> list = array.toJavaList(SummaryDataPoJo.class);
        if (CollectionsUtil.isEmpty(list)) {
            return list;
        }
        list.forEach(item -> {
            if (CollectionsUtil.isNotEmpty(item.getValue())) {
                item.getValue().removeIf(item1 -> StringUtil.isEmpty(item1.toString()));
            }
        });
        list.removeIf(item -> CollectionsUtil.isEmpty(item.getValue()));
        getTextSummaryList(list, contactExplainMap);
        handleSummaryCanSee(list, data, contactExplainMap, handlerExplainDTO, showPermission);
        getNoSpecialSummaryList(list, data);
        return list;
    }

    private void handleSummaryCanSee(List<SummaryDataPoJo> list, JSONObject contactData, Map<String, FieldAttrEntity> contactExplainMap, HandlerExplainDTO handlerExplainDTO, boolean showPermission) {
        List<String> noSpecialAttrList = new ArrayList<>();
        noSpecialAttrList.add(ContactEnum.IMPORTANT_DEGREE.getAttr());
        noSpecialAttrList.add(ContactEnum.INTIMATE_DEGREE.getAttr());
        // 权限过虑
        for (SummaryDataPoJo dataPoJo : list) {
            boolean canSee = commonHelp.attrCanSee(dataPoJo.getAttr(), contactExplainMap, handlerExplainDTO);
            canSee = canSee && showPermission;
            if (noSpecialAttrList.contains(dataPoJo.getAttr())) {
                Integer star = contactData.getInteger(dataPoJo.getAttr());
                if (!canSee) {
                    star = BasicConstant.ZERO;
                }
                List<Object> newValue = new ArrayList<>();
                newValue.add(star);
                dataPoJo.setValue(newValue);
            } else {
                if (!canSee) {
                    List<Object> newValue = new ArrayList<>();
                    for (int i = 0; i < dataPoJo.getValue().size(); i++) {
                        newValue.add("****");
                    }
                    dataPoJo.setValue(newValue);
                }
            }
        }
    }


    /**
     * 字段可见范围处理
     * @param attr 字段attr
     * @param data 数据
     * @param canSee 是否可见
     * @return
     */
    public Object handleAttrCanSee(String attr, JSONObject data, boolean canSee) {
        Object value = data.getOrDefault(attr, "");
        if (!canSee) {
            value = Objects.equals(ContactEnum.AVATAR.getAttr(), attr) ? "" : BasicConstant.NULL_SHOW_STR;
        }
        return value;
    }

    /***
     * 不要特殊处理的数据摘要和标签
     *
     * @param summaryList 数据摘要列表
     * @param: data
     * @throws
     * @return void
     * @author hongxiao
     * @date 2022-01-20 16:04
     * @since
     * @version
     */
    public void getNoSpecialSummaryList(List<SummaryDataPoJo> summaryList, JSONObject data) {
        if (CollectionsUtil.isEmpty(summaryList) || Objects.isNull(data)) {
            return;
        }
        List<String> noSpecialAttrList = new ArrayList<>();
        noSpecialAttrList.add(ContactEnum.IMPORTANT_DEGREE.getAttr());
        noSpecialAttrList.add(ContactEnum.INTIMATE_DEGREE.getAttr());
        for (SummaryDataPoJo dataPoJo : summaryList) {
            if (!noSpecialAttrList.contains(dataPoJo.getAttr())) {
                continue;
            }
            Integer star = data.getInteger(dataPoJo.getAttr());
            List<Object> list = new ArrayList<>();
            list.add(star);
            dataPoJo.setValue(list);
        }
    }

    private void getTextSummaryList(List<SummaryDataPoJo> list, Map<String, FieldAttrEntity> contactExplainMap) {
        for (SummaryDataPoJo dataPoJo : list) {
            FieldAttrEntity attrEntity = contactExplainMap.getOrDefault(dataPoJo.getAttr(), new FieldAttrEntityExt());
            List<ItemPoJo> items = attrEntity.getItems();
            if (CollectionsUtil.isEmpty(items)) {
                continue;
            }
            Map<String, Object> itemMap = new HashMap<>();
            items.forEach(itemPoJo -> itemMap.put(itemPoJo.getValue().toString(), itemPoJo.getText()));
            List<Object> value = dataPoJo.getValue();
            List<Object> newValue = new ArrayList<>();
            for (Object obj : value) {
                Object value1 = itemMap.getOrDefault(obj.toString(), obj);
                newValue.add(value1);
            }
            dataPoJo.setValue(newValue);
        }
    }
}
